package mwt.xml.xdbforms.schemalayer.types;

import javax.xml.XMLConstants;
import mwt.xml.xdbforms.dblayer.metadata.impl.ColumnMetaData;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;

/**
 * Definisce il tipo di dato Set per Xschema,
 * in questo set fornirà solo un tipo stringa,
 * ma sarà il controllo xform a forinre il corretto
 * controllo.
 * @author Gianfranco Murador, Matteo Ferri, Cristian Castiglia
 */
public class XmlSet extends XmlTypes {

    public XmlSet() {
    }

    public XmlSet(Document doc) {
        super(doc);
    }

    private void buildFragment(ColumnMetaData cmd) {


        Element xtype, restriction;
        Element pattern;

        fragment = doc.createDocumentFragment();
        xtype = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:simpleType");
        xtype.setAttribute("name", typeName);
        cmd.setXschemaTypeName(typeName);

        restriction = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:restriction");

        // Tutti le enumerazioni sono di tipo stringa o char
        restriction.setAttribute("base", "xs:string");

        pattern = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:pattern");

        String[] values = cmd.getEnumSetValues();

        String pattStr = "(";
        //String patternExp = "(*,*";

        //   String patternExp = "(*[' ']*";

        String patternExp = "([' ']";




        for (int i = 0; i < values.length; i++) {
            String value = values[i];
            pattStr += value + "|";
        }

        pattStr = pattStr.substring(0, pattStr.length() - 1);
        pattStr += ")";
        patternExp = pattStr + patternExp + pattStr + ")*";
        pattern.setAttribute("value", patternExp);
        restriction.appendChild(pattern);

        xtype.appendChild(restriction);
        fragment.appendChild(xtype);

    }

    @Override
    public DocumentFragment getSchemaType(ColumnMetaData cmd) {

        typeName = cmd.getTypeName();
        if (typeName.equals("SET")) {

            buildFragment(cmd);
            return fragment;

        } else {

            return nextType.getSchemaType(cmd);


        }

    }

    @Override
    public Object getXSchemaToJavaType(String baseType, String value) {
        if (baseType.startsWith("SET")) {

            return value.replace(' ', ',');

        } else {

            return nextType.getXSchemaToJavaType(baseType, value);
        }
    }
}

